import * as common from './common.js' //引入common
import * as db from './db.js' //引入db
import Base64 from './base64.js'


export const domain = 'https://域名:端口'
export const wssDomain = 'wss://域名:端口'
// export const domain = 'https://localhost:9999'
// export const wssDomain = 'ws://localhost:8090'

// 不需要登陆的，都写到这里
const methodsNotLogin = [
	'/user/login',
	'/wallpaper/getWallpaperList'
];
export const base64 = new Base64()
//POST方法
export const post = async (method, data, multipartHeard) => {
	// console.log("地址：", method, "请求数据：", data)
	return new Promise((resole, reject) => {
		let header = {
			'Content-Type': 'application/json;charset=UTF-8', //自定义请求头信息
			'Cookie': base64.encode(JSON.stringify(db.userInfo()))
		};
		if (multipartHeard) {
			header['Content-Type'] = multipartHeard;
		}
		// 判断token是否存在
		if (methodsNotLogin.indexOf(method) < 0) {
			// 获取用户token
			let token = db.token();
			if (!token) {
				common.jumpToLogin();
				return;
			}
			header.Authorization = token;
		}
		// uni.showLoading({
		// 	title: '加载中，请稍等...'
		// });
		uni.request({
			url: domain + method,
			header: header,
			data: data,
			method: 'POST',
			success: (response) => {
				// console.log("请求返回的数据", response)
				const result = response.data
				// 登录信息过期或者未登录
				if (!result.success) {
					if (result.code === 403 || result.errCode == 400) {
						db.del("userInfo");
						db.del('token')
						uni.showToast({
							title: "登录信息失效，请重新登录！",
							icon: 'none',
							duration: 400,
							complete: function() {
								setTimeout(function() {
									uni.hideToast();
									common.jumpToLogin()
								}, 600)
							}
						});
					} else if (result.errCode == 501) {
						uni.showModal({
							title: '积分不足',
							content: '账户积分不足',
							showCancel: true,
							confirmText: "去赚积分",
							success: res => {
								if (res.confirm) {
									//跳到看广告的页面
									common.switchTabTo(
										'/pages/mine/index');
								} else if (res.cancel) {

								}
							}
						});
					} else {
						uni.showToast({
							title: result.errMessage,
							icon: 'none',
							duration: 400,
						});
					}
					// reject
				} else {
					//放token
					const token = response.header['USER_LOGIN_TOKEN']
					if (token) {
						db.set('token', token)
					}
					// resole(result);
				}
				resole(result);
			},
			fail: (error) => {
				resole({});
				if (error && error.response) {
					showError(error.response);
				}
			},
		});
	})
}
//GET方法
export const get = async (url, data) => {
	// console.log("base:",base64.encode(JSON.stringify(db.userInfo())))
	return new Promise((resole, reject) => {
		let header = {
			'Cookie': base64.encode(JSON.stringify(db.userInfo()))
		}
		// console.log("地址：", url, "请求数据：", data, "headers", db.token())
		// 判断token是否存在
		if (methodsNotLogin.indexOf(url) < 0) {
			// 获取用户token
			let token = db.token();
			if (!token) {
				common.jumpToLogin();
				return;
			}
			header.Authorization = token;
		}
		// uni.showLoading({
		// 	title: '加载中,请稍等...'
		// });
		uni.request({
			url: domain + url,
			data: data,
			header: header,
			method: 'GET',
			success: (response) => {
				uni.hideLoading();
				const result = response.data
				if (!result.success) {
					if (result.errCode === 403 || result.errCode == 400) {
						db.del("userInfo");
						db.del('token')
						uni.showToast({
							title: "登录信息失效，请重新登录！",
							icon: 'none',
							duration: 400,
							complete: function() {
								setTimeout(function() {
									uni.hideToast();
									common.jumpToLogin()
								}, 600)
							}
						});
					} else if (result.errCode == 501) {
						uni.showModal({
							title: '积分不足',
							content: '账户积分不足',
							showCancel: true,
							confirmText: "去赚积分",
							success: res => {
								if (res.confirm) {
									//跳到看广告的页面
									common.switchTabTo(
										'/pages/mine/index');
								} else if (res.cancel) {

								}
							}
						});
					} else {
						uni.showToast({
							title: result.errMessage,
							icon: 'none',
							duration: 400,
						});
					}
					// reject
				}
				//如果响应token则更新token
				const token = response.header['USER_LOGIN_TOKEN']
				if (token) {
					db.set('token', token)
				}
				resole(result);
			},
			fail: (error) => {
				resole({});
				if (error && error.response) {
					showError(error.response);
				}
			},
			complete: () => {
				// uni.hideLoading();
			}
		});
	})
}
//统一处理请求错误
const showError = error => {
	let errorMsg = ''
	switch (error.status) {
		case 400:
			errorMsg = '请求参数错误'
			break
		case 401:
			errorMsg = '未授权，请登录'
			break
		case 403:
			errorMsg = '权限过期'
			break
		case 408:
			errorMsg = '请求超时'
			break
		case 500:
			errorMsg = '服务器内部错误'
			break
		case 501:
			errorMsg = '服务未实现'
			break
		case 502:
			errorMsg = '网关错误'
			break
		case 503:
			errorMsg = '服务不可用'
			break
		case 504:
			errorMsg = '网关超时'
			break
		case 505:
			errorMsg = 'HTTP版本不受支持'
			break
		default:
			errorMsg = error.msg
			break
	}

	uni.showToast({
		title: errorMsg,
		icon: 'none',
		duration: 1000,
		complete: function() {
			setTimeout(function() {
				uni.hideToast();
			}, 1000);
		}
	});
}
// 底部栏
export const tabbar = async (data) => await get('/api/v1/tabbar', data);